use crate::{mdb, code};
use axum::Json;
use mongodb::{options::GridFsBucketOptions, bson::Bson};
use serde_json::Value;

use super::upload_gridfs_move::get_bucket_name;
// 删除指定 id 
pub async fn one(object_id:&str, bucket_name:&str ) -> Result<(), Json<Value>>{

    let bucket_name = get_bucket_name(bucket_name)?;

    let id = mdb::to_object_id(object_id.to_string());

    let conn = mdb::connect().await?;
    
    let options = GridFsBucketOptions::builder().bucket_name(bucket_name.to_string()).build();
    let bucket = conn.gridfs_bucket(options);
    match bucket.delete(id).await {
        Ok(_f) => Ok(()),
        Err(e) => Err(code::sys_(e.to_string()))
    }
}
// 删除多个 id 
pub async fn many(files:Vec<Value>, bucket_name:&str ) -> Result<(), Json<Value>>{
    let conn = mdb::connect().await?;
    
    let options = GridFsBucketOptions::builder().bucket_name(bucket_name.to_string()).build();
    let bucket = conn.gridfs_bucket(options);

    for v in files{
        let id = mdb::to_object_id(v.as_str().unwrap());
        let _ = match bucket.delete(id).await {
            Ok(_f) => Ok(()),
            Err(e) => Err(code::sys(e.to_string()))
        };
    }
    Ok(())
}
// 删除指定 id 
pub async fn delete_by_bson(object_id:Bson, bucket_name:&str ) -> Result<(), Json<Value>>{
    let conn = mdb::connect().await?;
    let options = GridFsBucketOptions::builder().bucket_name(bucket_name.to_string()).build();
    let bucket = conn.gridfs_bucket(options);
    match bucket.delete(object_id).await {
        Ok(_f) => Ok(()),
        Err(_e) => Err(code::sys_("删除失败"))
    }
}